package com.swz.dcrm.ui.home;


import android.animation.ValueAnimator;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.Clue;
import com.swz.dcrm.model.ClueRecord;
import com.swz.dcrm.model.Dictionary;
import com.swz.dcrm.model.Schedule;
import com.swz.dcrm.model.SuggestLevel;
import com.swz.dcrm.model.VisitRecord;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import ezy.ui.view.RoundButton;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CustomerManagementViewModel;
import com.swz.dcrm.ui.viewmodel.ScheduleViewModel;
import com.swz.dcrm.util.Constant;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.Tool;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class AddVisitRecordFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_follow_way)
    TextView tvFollowWay;
    @BindView(R.id.tv_chat_result)
    TextView tvChatResult;
    @BindView(R.id.tv_contact_result)
    TextView tvContactResult;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_next_follow_purpose)
    TextView tvNextFollowPurpose;
    @BindView(R.id.tv_next_way)
    TextView tvNextWay;
    @BindView(R.id.tv_next_date)
    TextView tvNextDate;
    @BindView(R.id.tv_destination)
    TextView tvDestination;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.et_record_dec)
    EditText etRecordDec;
    @BindView(R.id.et_next_dec)
    EditText etNextDec;
    @BindView(R.id.cb_add_schedule)
    CheckBox cbAddSchedule;
    @BindView(R.id.cb_fail)
    CheckBox cbFail;
    @BindView(R.id.ll_level)
    LinearLayout llLevel;
    @BindView(R.id.tv_suggestion)
    TextView tvSuggestion;
    @BindView(R.id.btn_accept)
    RoundButton btnAccept;
    @BindView(R.id.btn_no)
    RoundButton btnNo;




    @Inject
    CustomerManagementViewModel customerManagementViewModel;
    @Inject
    ScheduleViewModel scheduleViewModel;

    private TimePickerView timePickerView;

    private List<Dictionary> clueFollowType;
    private List<Dictionary> cluePhoneResult;
    private List<Dictionary> clueContactResult;
    private List<Dictionary> clueFollowPurpose;
    private List<Dictionary> clueCustomerLevel;

    ActionSheetDialog actionSheetDialog;
    private int height;
    private ValueAnimator valueAnimator;


    private ClueRecord clueRecord;

    private boolean clickable=true;

    private VisitRecord visitRecord=new VisitRecord();

    public static AddVisitRecordFragment newInstance() {

        return new AddVisitRecordFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_clueFollowType)
                .observe(this, listBaseResponse -> {
                    if(listBaseResponse.isSuccess()){
                        clueFollowType=listBaseResponse.getData();

                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_clueContactResult)
                .observe(this, listBaseResponse -> {
                    if(listBaseResponse.isSuccess()){
                        cluePhoneResult=listBaseResponse.getData();
                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_clueCustomerLevel)
                .observe(this, listBaseResponse -> {
                    if(listBaseResponse.isSuccess()){
                        clueCustomerLevel=listBaseResponse.getData();

                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_cluePhoneResult)
                .observe(this, listBaseResponse -> {
                    if(listBaseResponse.isSuccess()){
                        clueContactResult=listBaseResponse.getData();
                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_clueFollowPurpose)
                .observe(this, listBaseResponse -> {
                    if(listBaseResponse.isSuccess()){
                        clueFollowPurpose=listBaseResponse.getData();

                    }
                });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_add_visit_record;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        tvRight.setText(getString(R.string.add_visit_record_save));
        height = Tool.dip2px(getActivity(), 87);
        timePickerView=getTimePickerView((date, v) -> {
            tvNextDate.setText(DateUtils.dateFormat(date,"yyyy-MM-dd"));
        }).build();

        AddVisitRecordFragmentArgs addVisitRecordFragmentArgs=AddVisitRecordFragmentArgs.fromBundle(getArguments());
        if(addVisitRecordFragmentArgs.getVisitRecord().equals("test")){

            clueRecord=new Gson().fromJson(addVisitRecordFragmentArgs.getClueRecord(), ClueRecord.class);
            visitRecord.setClueId(clueRecord.getBsClueVO().getId());

            if(clueRecord.getNextFollowType()==0){
                tv.setVisibility(View.GONE);
                tvDestination.setVisibility(View.GONE);
            }
            if(clueRecord.getNextFollowType()!=0){
                visitRecord.setFollowType(clueRecord.getNextFollowType());
                visitRecord.setFollowPurpose(clueRecord.getNextFollowPurpose());
                tvFollowWay.setText(clueRecord.getNextFollowTypeDesc());
                tvDestination.setText(clueRecord.getNextFollowPurposeDesc());
            }
            if(clueRecord.getBsClueVO().getLevelDesc()!=null){
                tvLevel.setText(clueRecord.getBsClueVO().getLevelDesc());
                visitRecord.setLevel(clueRecord.getBsClueVO().getLevel());
            }
            title.setText(getString(R.string.add_visit_record_title));
        }else {
            visitRecord=new Gson().fromJson(addVisitRecordFragmentArgs.getVisitRecord(),VisitRecord.class);
            clickable=false;
            title.setText(getString(R.string.add_visit_record_title1));
            tvRight.setText("");

                tv.setVisibility(View.GONE);
                tvDestination.setVisibility(View.GONE);

            if(!TextUtils.isEmpty(visitRecord.getFollowTypeDesc())){
                tvFollowWay.setText(visitRecord.getFollowTypeDesc());
            }
            if(!TextUtils.isEmpty(visitRecord.getPhoneResultDesc())){
                tvContactResult.setText(visitRecord.getPhoneResultDesc());
            }
            if(!TextUtils.isEmpty(visitRecord.getContactResultDesc())){
                tvChatResult.setText(visitRecord.getContactResultDesc());
            }
            if(!TextUtils.isEmpty(visitRecord.getLevelDesc())){
                tvLevel.setText(visitRecord.getLevelDesc());
            }
            if(!TextUtils.isEmpty(visitRecord.getRemark())){
                etRecordDec.setText(visitRecord.getRemark());
            }
            if(!TextUtils.isEmpty(visitRecord.getNextFollowTime())){
                tvNextDate.setText(DateUtils.dateFormat(visitRecord.getNextFollowTime(),"yyyy-MM-dd"));
            }
            if(!TextUtils.isEmpty(visitRecord.getNextFollowTypeDesc())){
                tvNextWay.setText(visitRecord.getNextFollowTypeDesc());
            }
            if(!TextUtils.isEmpty(visitRecord.getNextFollowPurposeDesc())){
                tvNextFollowPurpose.setText(visitRecord.getNextFollowPurposeDesc());
            }
            if(!TextUtils.isEmpty(visitRecord.getNextFollowRemark())){
                etNextDec.setText(visitRecord.getNextFollowRemark());
            }
        }
        return true;
    }

    public void showLevelSuggestion(boolean show){
        int start;
        int end;
        ViewGroup.LayoutParams layoutParams = llLevel.getLayoutParams();
        if(show){
            if(layoutParams.height==height){
                return;
            }
            start=0;
            end=height;
        }else {
            if(layoutParams.height==0){
                return;
            }
            start=height;
            end=0;
        }


        valueAnimator = ValueAnimator.ofInt(start, end);
        valueAnimator.addUpdateListener(animation -> {

            layoutParams.height = (int) animation.getAnimatedValue();
            llLevel.setLayoutParams(layoutParams);
        });
        valueAnimator.setDuration(100);
        valueAnimator.start();

    }
    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick(R.id.ll_next_date)
    public void nextDate(){
        if(clickable){
            timePickerView.show();
        }

    }
    @OnClick({R.id.ll_way, R.id.ll_change, R.id.ll_chat_result,R.id.ll_contact_result,R.id.ll_next_follow_purpose,R.id.ll_next_follow_way})
    public void click(View view) {
        if(!clickable){
            return;
        }
        List<String> list=new ArrayList<>();
        switch (view.getId()) {
            case R.id.ll_next_follow_way:
            case R.id.ll_way:
                for(Dictionary dictionary:clueFollowType){

                    list.add(dictionary.getName());
                }
                break;
            case R.id.ll_change:
                for(Dictionary dictionary:clueCustomerLevel){
                    list.add(dictionary.getName());
                }
                break;
            case R.id.ll_chat_result:
                for(Dictionary dictionary:cluePhoneResult){
                    list.add(dictionary.getName());
                }
                break;
            case R.id.ll_contact_result:
                for(Dictionary dictionary:clueContactResult){
                    list.add(dictionary.getName());
                }
                break;
            case R.id.ll_next_follow_purpose:
                for(Dictionary dictionary:clueFollowPurpose){
                    list.add(dictionary.getName());
                }
                break;
        }
        String[] s=new String[]{};
        actionSheetDialog=new ActionSheetDialog(getContext(),list.toArray(s),null);
        actionSheetDialog.setOnOperItemClickL((parent, view1, position, id) -> {
            switch (view.getId()) {
                case R.id.ll_way:
                    tvFollowWay.setText(list.get(position));
                    visitRecord.setFollowType(clueFollowType.get(position).getCode());
                    break;
                case R.id.ll_change:
                    tvLevel.setText(list.get(position));
                    visitRecord.setLevel(clueCustomerLevel.get(position).getCode());
                    break;
                case R.id.ll_chat_result:
                    tvChatResult.setText(list.get(position));
                    visitRecord.setContactResult(cluePhoneResult.get(position).getCode());
                    if(visitRecord.getContactResult()!=null&&visitRecord.getPhoneResult()!=null){
                        customerManagementViewModel.getSuggestLevel(clueRecord.getBsClueVO().getId(),visitRecord.getContactResult(),
                                visitRecord.getPhoneResult()).observe(this, suggestLevelBaseResponse -> {
                                    if(suggestLevelBaseResponse!=null&& suggestLevelBaseResponse.getData().getCode()!=visitRecord.getLevel()){
                                        tvSuggestion.setText(getString(R.string.add_visit_record_level,suggestLevelBaseResponse.getData().getName()));
                                        showLevelSuggestion(true);
                                        btnAccept.setOnClickListener(v -> {
                                            tvLevel.setText(suggestLevelBaseResponse.getData().getName());
                                            visitRecord.setLevel(suggestLevelBaseResponse.getData().getCode());
                                            visitRecord.setLevelDesc(suggestLevelBaseResponse.getData().getName());
                                            showLevelSuggestion(false);
                                        });
                                        btnNo.setOnClickListener(v -> {
                                            showLevelSuggestion(false);
                                        });
                                    }else if(suggestLevelBaseResponse!=null){
                                        showLevelSuggestion(false);
                                    }
                                });

                    }
                    break;
                case R.id.ll_contact_result:
                    tvContactResult.setText(list.get(position));
                    visitRecord.setPhoneResult(clueContactResult.get(position).getCode());
                    if(visitRecord.getContactResult()!=null&&visitRecord.getPhoneResult()!=null){

                        customerManagementViewModel.getSuggestLevel(clueRecord.getBsClueVO().getId(),visitRecord.getContactResult(),
                                visitRecord.getPhoneResult()).observe(this, suggestLevelBaseResponse -> {
                            if(suggestLevelBaseResponse!=null&& suggestLevelBaseResponse.getData().getCode()!=visitRecord.getLevel()){
                                tvSuggestion.setText(getString(R.string.add_visit_record_level,suggestLevelBaseResponse.getData().getName()));
                                showLevelSuggestion(true);
                                btnAccept.setOnClickListener(v -> {
                                    tvLevel.setText(suggestLevelBaseResponse.getData().getName());
                                    visitRecord.setLevel(suggestLevelBaseResponse.getData().getCode());
                                    visitRecord.setLevelDesc(suggestLevelBaseResponse.getData().getName());
                                    showLevelSuggestion(false);
                                });
                                btnNo.setOnClickListener(v -> {
                                    showLevelSuggestion(false);
                                });
                            }else if(suggestLevelBaseResponse!=null){
                                showLevelSuggestion(false);
                            }
                                });
                    }
                    break;
                case R.id.ll_next_follow_purpose:
                    tvNextFollowPurpose.setText(list.get(position));
                    visitRecord.setNextFollowPurpose(clueFollowPurpose.get(position).getCode());
                    break;
                case R.id.ll_next_follow_way:
                    tvNextWay.setText(list.get(position));
                    visitRecord.setNextFollowType(clueFollowType.get(position).getCode());
                    break;
            }
            actionSheetDialog.dismiss();
        });
        actionSheetDialog.isTitleShow(false);
        actionSheetDialog.show();

    }

    @OnClick(R.id.tv_right)
    public void  save(){
        if(visitRecord.getFollowType()==null){
            showToast(getString(R.string.add_customer_hint_select)+getString(R.string.add_visit_record_way));
            return;
        }
        if(visitRecord.getPhoneResult()==null){
            showToast(getString(R.string.add_customer_hint_select)+getString(R.string.add_visit_record_contact_result));
            return;
        }
        if(visitRecord.getLevel()==null){
            showToast(getString(R.string.add_customer_hint_select)+getString(R.string.add_visit_record_change_level));
            return;
        }
        if(TextUtils.isEmpty(etRecordDec.getText().toString())){
            showToast(getString(R.string.add_visit_record_visit_record_hint));
            etRecordDec.requestFocus();
            return;
        }else {
            visitRecord.setRemark(etRecordDec.getText().toString());
        }
        if(TextUtils.isEmpty(tvNextDate.getText().toString())){
            showToast(getString(R.string.add_customer_hint_select)+getString(R.string.add_visit_record_visit_next_date));
            return;
        }else {
            visitRecord.setNextFollowTime(tvNextDate.getText().toString());
        }
        if(TextUtils.isEmpty(tvNextWay.getText().toString())){
            showToast(getString(R.string.add_customer_hint_select)+getString(R.string.add_visit_record_visit_next_way));
            return;
        }
        if(TextUtils.isEmpty(tvNextFollowPurpose.getText().toString())){
            showToast(getString(R.string.add_customer_hint_select)+getString(R.string.add_visit_record_visit_next_destination));
            return;
        }
        if(TextUtils.isEmpty(etNextDec.getText().toString())){
            showToast(getString(R.string.add_visit_record_visit_next_plan_hint));
            etNextDec.requestFocus();
            return;
        }else {
            visitRecord.setNextFollowRemark(etNextDec.getText().toString());
        }
        if(visitRecord.getId()!=null){
            customerManagementViewModel.updateVisitRecord(visitRecord)
                    .observe(this, visitRecordBaseResponse -> {
                        if(visitRecordBaseResponse==null){
                            return;
                        }
                        showToast(visitRecordBaseResponse.getMsg());
                    });
            return;
        }

        customerManagementViewModel.addRecordAndSchedule(false,visitRecord,null,cbFail.isChecked())
                .observe(this, visitRecordBaseResponse -> {
                    if(visitRecordBaseResponse==null){
                        return;
                    }
                    if(visitRecordBaseResponse.isSuccess()){
                        if(cbAddSchedule.isChecked()){
                            Schedule schedule=new Schedule();
                            schedule.setStartTime(tvNextDate.getText().toString()+" 00:00:00");
                            schedule.setEndTime(tvNextDate.getText().toString()+" 23:59:59");
                            schedule.setCustomerId(clueRecord.getClueId());
                            schedule.setTag(2);
                            schedule.setBeforeMinuteRemind(5);
                            schedule.setContext(getString(R.string.add_visit_record_next_plan)+":"+etNextDec.getText().toString());
                            scheduleViewModel.addSchedule(schedule);
                        }
                            backClick();
                    }else {
                        if(visitRecordBaseResponse.getCode()==10501){
                            backClick();
                        }
                        showToast(visitRecordBaseResponse.getMsg());
                    }
                });
    }
}
